package cn.enjoyedu.fksum.service;

import cn.enjoyedu.fksum.dao.DbUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

@Service
public class FkSum {

    @Autowired
    private DbUtils dbUtils;

    private static class SumTask extends RecursiveTask<Long> {
        private int startId;
        private int endId;
        private DbUtils dbUtils;

        public SumTask(int startId, int endId, DbUtils dbUtils) {
            this.startId = startId;
            this.endId = endId;
            this.dbUtils = dbUtils;
        }

        //使用ForkJoinPool调用invoke()时,底层核心调用compute()方法
        @Override
        protected Long compute() {
            //如果满足条数小于 5000
            if (endId - startId < SingleThread.THRESHOLD) {
                //执行最小粒度任务
                return dbUtils.sumRecorders(endId, startId);
            } else {
                //fromIndex....mid.....toIndex
                int mid = (startId + endId) / 2;//折半,将数据分成左右两部分
                SumTask left = new SumTask(startId, mid, dbUtils);//左边数据
                SumTask right = new SumTask(mid + 1, endId, dbUtils);//右边数据
                invokeAll(left, right);//递归调用compute(),是否满足if条件,满足计算,不满足继续拆
                long leftResult = left.join();
                long rightResult = right.join();
                return leftResult + rightResult;
            }
        }
    }

    public void sum() {
        //核心类
        ForkJoinPool pool = new ForkJoinPool(64);

        long start = System.currentTimeMillis();
        int recordMin = dbUtils.getMin();//从数据库获取最小ID号
        int recordMax = dbUtils.getMax();//从数据库获取最大ID号
        SumTask sumTask = new SumTask(recordMin,
                recordMax, dbUtils);//初始化总任务:1亿数据库查询的任务

        pool.invoke(sumTask);//拆分 计算  调用invoke, 实际是执行compute()
        System.out.println("Task is Running.....");

        System.out.println("The sum is " + sumTask.join()
                + " spend time:" + (System.currentTimeMillis() - start) + "ms");
    }

}
